package com.example.hibernate.demo.service;

import com.example.hibernate.demo.entity.Order;
import com.example.hibernate.demo.entity.OrderItem;
import com.example.hibernate.demo.entity.Product;
import com.example.hibernate.demo.repository.OrderRepository;
import com.example.hibernate.demo.repository.ProductRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderService {
    
    private final OrderRepository orderRepository;
    private final ProductRepository productRepository;
    
    @Transactional(readOnly = true)
    public List<Order> findAll() {
        return orderRepository.findAll();
    }
    
    @Transactional(readOnly = true)
    public Order findById(Long id) {
        return orderRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Order not found with id: " + id));
    }
    
    @Transactional(readOnly = true)
    public Order findByIdWithItems(Long id) {
        return orderRepository.findByIdWithItems(id);
    }
    
    @Transactional(readOnly = true)
    public List<Order> findByStatus(Order.OrderStatus status) {
        return orderRepository.findByStatus(status);
    }
    
    @Transactional(readOnly = true)
    public List<Order> findByCustomerEmail(String email) {
        return orderRepository.findByCustomerEmail(email);
    }
    
    @Transactional
    public Order save(Order order) {
        // 计算订单总金额
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            BigDecimal total = BigDecimal.ZERO;
            for (OrderItem item : order.getItems()) {
                total = total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
            }
            order.setTotalAmount(total);
        }
        return orderRepository.save(order);
    }
    
    @Transactional
    public Order addItemToOrder(Long orderId, Long productId, int quantity) {
        Order order = orderRepository.findByIdWithItems(orderId);
        if (order == null) {
            throw new EntityNotFoundException("Order not found with id: " + orderId);
        }
        
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new EntityNotFoundException("Product not found with id: " + productId));
        
        // 检查是否已存在该商品
        boolean itemExists = false;
        for (OrderItem item : order.getItems()) {
            if (item.getId().getProductId().equals(productId)) {
                // 更新数量
                item.setQuantity(item.getQuantity() + quantity);
                itemExists = true;
                break;
            }
        }
        
        // 如果不存在，添加新项目
        if (!itemExists) {
            OrderItem newItem = new OrderItem();
            newItem.setId(new OrderItem.OrderItemId(orderId, productId));
            newItem.setOrder(order);
            newItem.setProduct(product);
            newItem.setQuantity(quantity);
            newItem.setPrice(product.getPrice());
            order.addItem(newItem);
        }
        
        // 重新计算总金额
        BigDecimal total = BigDecimal.ZERO;
        for (OrderItem item : order.getItems()) {
            total = total.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }
        order.setTotalAmount(total);
        
        return orderRepository.save(order);
    }
    
    @Transactional
    public Order updateOrderStatus(Long id, Order.OrderStatus status) {
        Order order = findById(id);
        order.setStatus(status);
        return orderRepository.save(order);
    }
    
    @Transactional
    public void delete(Long id) {
        Order order = findById(id);
        orderRepository.delete(order);
    }
}